package com.ruoyi.web.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.web.controller.common.AiQuestionService;
import com.ruoyi.web.domain.News;
import com.ruoyi.web.domain.OldQuestion;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.web.mapper.QuestionMapper;
import com.ruoyi.web.domain.Question;
import com.ruoyi.web.service.IQuestionService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 问答管理（新）Service业务层处理
 * 
 * @author drx
 * @date 2024-03-18
 */
@Service
public class QuestionServiceImpl implements IQuestionService 
{
    @Resource
    private QuestionMapper questionMapper;

    @Resource
    private AiQuestionService aiQuestionService;

    /**
     * 查询问答管理（新）
     * 
     * @param id 问答管理（新）主键
     * @return 问答管理（新）
     */
    @Override
    public Question selectQuestionById(Long id)
    {
        return questionMapper.selectQuestionById(id);
    }

    public AjaxResult getQuestionById(Long id)
    {
        {
            AjaxResult ajaxResult=new AjaxResult();
            try{
                Question question = questionMapper.selectQuestionById(id);
                if(null != question){
                    //状态为未启用时，返回空对象
                    if("0".equals(question.getState())){
                        ajaxResult.put("data",null);
                        ajaxResult.put("code","1");
                        ajaxResult.put("msg","查询成功！");
                        return  ajaxResult;
                    }
                }
                ajaxResult.put("data",question);
                ajaxResult.put("code","1");
                ajaxResult.put("msg","查询成功！");
            } catch (Exception e){

                e.printStackTrace();
                ajaxResult.put("code","500");
                ajaxResult.put("msg","获取药品详情失败，请联系管理员！");
            }
            return ajaxResult;
        }
    }


    /**
     * 查询问答管理（新）列表
     * 
     * @param question 问答管理（新）
     * @return 问答管理（新）
     */
    @Override
    public List<Question> selectQuestionList(Question question)
    {
        return questionMapper.selectQuestionList(question);
    }

    /**
     * 新增问答管理（新）
     * 
     * @param question 问答管理（新）
     * @return 结果
     */
    @Override
    public int insertQuestion(Question question)
    {
        question.setCreateTime(DateUtils.getNowDate());
        question.setCreateBy(ShiroUtils.getSysUser().getLoginName());
        question.setCreateName(ShiroUtils.getSysUser().getUserName());
        question.setUpdateTime(DateUtils.getNowDate());
        question.setUpdateBy(ShiroUtils.getSysUser().getLoginName());
        question.setUpdateName(ShiroUtils.getSysUser().getUserName());
        question.setHits(500L);
        return questionMapper.insertQuestion(question);
    }

    /**
     * 修改问答管理（新）
     * 
     * @param question 问答管理（新）
     * @return 结果
     */
    @Override
    public int updateQuestion(Question question)
    {
        question.setUpdateTime(DateUtils.getNowDate());
        question.setUpdateBy(ShiroUtils.getSysUser().getLoginName());
        question.setUpdateName(ShiroUtils.getSysUser().getUserName());
        return questionMapper.updateQuestion(question);
    }

    /**
     * 批量删除问答管理（新）
     * 
     * @param ids 需要删除的问答管理（新）主键
     * @return 结果
     */
    @Override
    public int deleteQuestionByIds(String ids)
    {
        return questionMapper.deleteQuestionByIds(Convert.toStrArray(ids),ShiroUtils.getSysUser().getLoginName());
    }

    /**
     * 删除问答管理（新）信息
     * 
     * @param id 问答管理（新）主键
     * @return 结果
     */
    @Override
    public int deleteQuestionById(Long id)
    {
        return questionMapper.deleteQuestionById(id,ShiroUtils.getSysUser().getLoginName());
    }

    /**
     * 修改问题发布状态
     *
     * @param question
     * @return 结果
     */
    @Transactional
    public int updateQuestionState(Question question)
    {
        question.setUpdateTime(DateUtils.getNowDate());
        question.setUpdateBy(ShiroUtils.getSysUser().getLoginName());
        question.setUpdateName(ShiroUtils.getSysUser().getUserName());
        return questionMapper.updateQuestion(question);
    }


    /*
     * 根据id查询上一篇下一篇
     * */
    @Override
    public AjaxResult getUpandDown(Long id) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            List<HashMap<String, Object>> upandDown = questionMapper.getUpandDown(id);
            ajaxResult.put("data", upandDown);
            ajaxResult.put("code", "200");
            ajaxResult.put("msg", "查询成功！");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", "500");
            ajaxResult.put("msg", "获取问答上下篇失败，请联系管理员！");
        }
        return ajaxResult;
    }
    /**
     * 获取首页-药品知识
     *
     * @return AjaxResult
     */
    public AjaxResult getQuestionListView(){
        AjaxResult ajaxResult = new AjaxResult();
        try{
            List<Question> list= questionMapper.getQuestionListView();
            ajaxResult.put("data",list);
            ajaxResult.put("code", Constants.SUCCESS);
            ajaxResult.put("msg","查询成功！");
        }catch (Exception e){
            e.printStackTrace();
            ajaxResult.put("code",Constants.FAIL);
            ajaxResult.put("msg","获取药品问答失败，请联系管理员！");
        }
        return ajaxResult;
    }
    /*
    * 增加浏览量
    * */
    public void updateQuesBrowseNum(Long id){
        questionMapper.updateQuesBrowseNum(id);
    }

    public AjaxResult addQustionByAi(Question question) {
        AjaxResult ajaxResult = new AjaxResult();

        if (Objects.isNull(question) || Strings.isEmpty(question.getName().trim())) {
            ajaxResult.put("code", "500");
            ajaxResult.put("msg", "请传入需要生成文案的标题关键词!");
            return ajaxResult;
        }

        String[] split = question.getName().split("\\r?\\n|\\r");

        try {
            com.alibaba.fastjson.JSONObject dialogue = aiQuestionService.init();

            if (!Objects.isNull(dialogue) && !Objects.isNull(dialogue.get("conversation_id"))) {

                for (int i = 0; i < split.length; i++) {
                    if (Strings.isEmpty(split[i].trim())) {
                        continue;
                    }

                    com.alibaba.fastjson.JSONObject conversationResponse = aiQuestionService.sendRequest(split[i].trim(), dialogue.getString("conversation_id"));
                    if (!Objects.isNull(conversationResponse) && !Objects.isNull(conversationResponse.get("answer"))) {
                        String answer = conversationResponse.getString("answer");

                        Question que = new Question();
                        que.setName(split[i]);
                        que.setCreateBy("ai");
                        que.setContracteddesign(answer);
                        que.setCreateTime(DateUtils.getNowDate());
                        int x = questionMapper.insertQuestion(que);

                        if (x > 0) {
                            ajaxResult.put("code", "200");
                            ajaxResult.put("msg", "生成成功!");
                        } else {
                            ajaxResult.put("code", "200");
                            ajaxResult.put("msg", "生成失败,请联系管理员!");
                        }
                    } else {
                        ajaxResult.put("code", "500");
                        ajaxResult.put("msg", "引入会话失败,请联系管理员!");
                        return ajaxResult;
                    }

                }
            } else {
                ajaxResult.put("code", "500");
                ajaxResult.put("msg", "新建会话失败,请联系管理员!");
                return ajaxResult;
            }

        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", "500");
            ajaxResult.put("msg", "新建会话失败,请联系管理员!");
            return ajaxResult;
        }
        return ajaxResult;
    }
}
